package com.hengpeng.itfin.job.mail.support;

import java.util.Date;
import java.util.Properties;

import javax.mail.internet.MimeMessage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import com.hengpeng.common.cis.ComponentContextLoader;
import com.hengpeng.itfin.common.SystemConfigUtil;
import com.hengpeng.itfin.service.ServiceFactory;
import com.hengpeng.itfinbase.persist.EmailLog;
import com.hengpeng.itfinbase.persist.EmailLog.EmailState;



/**
 * <pre>
 * 邮件发送执行器
 * </pre>
 * @author shanguogang
 * @version 1.0, 2015-7-31
 */
public class EmailHandler implements Runnable
{
	// private int errorNum=0;
	private static final Log log = LogFactory.getLog(EmailHandler.class);

	private EmailLog email;

	public EmailHandler(EmailLog email)
	{
		this.email = email;
	}

	public void run()
	{
		sendMail();
		log.info("向用户名[" + email.getUsername() + "]投注卡号[" + email.getUsername() + "]的邮箱[" + email.getEmail()
				+ "]的邮件已发送。邮件对象ID:[" + email.getId() + "]");

	}

	private void sendMail()
	{
		Date startDate = new Date();
		ServiceFactory serviceFactory = ComponentContextLoader.getBean("serviceFactory", ServiceFactory.class);

		JavaMailSenderImpl javaMail = new JavaMailSenderImpl();
		javaMail.setHost(SystemConfigUtil.getConfigValue("mail.smtp.host"));
		javaMail.setPassword(SystemConfigUtil.getConfigValue("mail.from.password"));
		javaMail.setUsername(SystemConfigUtil.getConfigValue("mail.from"));
		Properties prop = new Properties();
		prop.setProperty("mail.smtp.auth", "true");
		prop.setProperty("mail.smtp.timeout", SystemConfigUtil.getConfigValue("mail.from.password"));
		javaMail.setJavaMailProperties(prop);
		MimeMessage message = javaMail.createMimeMessage();
		try
		{
			MimeMessageHelper messageHelp = new MimeMessageHelper(message, true, "utf-8");
			messageHelp.setFrom(SystemConfigUtil.getConfigValue("mail.from"));
			messageHelp.setTo(email.getEmail());
			messageHelp.setSubject(email.getTitle());
			messageHelp.setText(email.getContent(), true);
			javaMail.send(message);

		}
		catch (Exception e)
		{
			log.error("error-发送邮件异常" + e);
			EmailLog emailLog = serviceFactory.getPersistService().get(EmailLog.class, email.getId());
			emailLog.setState(EmailState.NOTSEND);
			serviceFactory.getPersistService().update(emailLog);
			return;
		}
		EmailLog emailLog = serviceFactory.getPersistService().get(EmailLog.class, email.getId());
		emailLog.setSendUserName(javaMail.getUsername());
		emailLog.setSendTime(startDate);
		emailLog.setSuccessTime(new Date());
		emailLog.setState(EmailState.SENDED);
		serviceFactory.getPersistService().update(emailLog);
	}

	public EmailLog getEmail()
	{
		return email;
	}

	public void setEmail(EmailLog email)
	{
		this.email = email;
	}

}
